<?php

namespace App\Exceptions;

use App\CodeResponse;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Validation\ValidationException;
use Throwable;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that are not reported.
     *
     * @var array<int, class-string<Throwable>>
     */
    protected $dontReport
        = [
            BusinessException::class
        ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array<int, string>
     */
    protected $dontFlash
        = [
            'current_password',
            'password',
            'password_confirmation',
        ];

    /**
     * Register the exception handling callbacks for the application.
     *
     * @return void
     */
    public function register()
    {
        $this->reportable(function (Throwable $e) {
            //
        });
    }

    /**
     * 自定义异常
     *
     * @param $request
     * @param  Throwable  $e
     *
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Response|\Symfony\Component\HttpFoundation\Response
     */
    public function render($request, Throwable $e)
    {
        /*return response()->json([
            'code' => $e->getCode() ?? 1,
            'file' => $e->getFile(), //获取出错误的文件
            'line' => $e->getLine(), //获取错误在哪一行
            'message' => $e->getMessage() ?? "error!",
            'data' => []
        ]);*/
        // 如果接收到数据验证错误
        if($e instanceof ValidationException) {
            return response()->json([
                'errno' => CodeResponse::PARAM_VALUE_ILLEGAL[0],
                'errmsg' => CodeResponse::PARAM_VALUE_ILLEGAL[1]
            ]);
        }
        // 如果接收到业务异常
        if ($e instanceof BusinessException) {
            return response()->json(['errno' => $e->getCode(), 'errmsg' => $e->getMessage()]);
        }
        return parent::render($request, $e);
    }
}
